package com.greate.community.controller;

import com.greate.community.entity.Post;
import com.greate.community.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/posts")
public class PostController {

    @Autowired
    private PostService postService;

    // 获取帖子列表
    @GetMapping
    public List<Post> getPosts() {
        return postService.findAllPosts();
    }

    // 获取单个帖子
    @GetMapping("/{id}")
    public Post getPost(@PathVariable int id) {
        return postService.findPostById(id);
    }

    // 获取用户的帖子
    @GetMapping("/user/{userId}")
    public List<Post> getUserPosts(@PathVariable int userId) {
        return postService.findPostsByUserId(userId);
    }

    // 创建帖子
    @PostMapping
    public Map<String, Object> createPost(@RequestBody Post post) {
        Map<String, Object> result = new HashMap<>();
        int status = postService.addPost(post);
        result.put("success", status > 0);
        result.put("message", status > 0 ? "创建成功" : "创建失败");
        return result;
    }

    // 更新帖子
    @PutMapping("/{id}")
    public Map<String, Object> updatePost(@PathVariable int id, @RequestBody Post post) {
        Map<String, Object> result = new HashMap<>();
        post.setId(id);
        int status = postService.updatePost(post);
        result.put("success", status > 0);
        result.put("message", status > 0 ? "更新成功" : "更新失败");
        return result;
    }

    // 删除帖子
    @DeleteMapping("/{id}")
    public Map<String, Object> deletePost(@PathVariable int id) {
        Map<String, Object> result = new HashMap<>();
        int status = postService.deletePost(id);
        result.put("success", status > 0);
        result.put("message", status > 0 ? "删除成功" : "删除失败");
        return result;
    }

    // 更新帖子状态
    @PutMapping("/{id}/status")
    public Map<String, Object> updatePostStatus(@PathVariable int id, @RequestParam int status) {
        Map<String, Object> result = new HashMap<>();
        int updateStatus = postService.updatePostStatus(id, status);
        result.put("success", updateStatus > 0);
        result.put("message", updateStatus > 0 ? "状态更新成功" : "状态更新失败");
        return result;
    }

    // 更新帖子类型
    @PutMapping("/{id}/type")
    public Map<String, Object> updatePostType(@PathVariable int id, @RequestParam int type) {
        Map<String, Object> result = new HashMap<>();
        int status = postService.updatePostType(id, type);
        result.put("success", status > 0);
        result.put("message", status > 0 ? "类型更新成功" : "类型更新失败");
        return result;
    }
} 